<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="en">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "85ee2976"
    });
  daovoice('update');
  </script>
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">


  <link rel="manifest" href="/images/favicon.ico">




  <meta name="keywords" content="hexo，Next">










<meta name="description" content="原理k 临近算法，是机器学习（监督学习）的一种经典的分类算（当然也能解决其他的一些问题，例如线性回归） 官方解释：存在一个样本数据集，也称作训练样本集，并且样本中每个数据都存在标签，即我们知道样本集中每一数据与所属分类的对应关系，输入没有标签的新数据后，将新数据的每个特征与样本集中的数据对应的特征进行比较，然后算法提取样本集中特征最相似的数据（最近邻）的分类标签。一般来说，我们只选择样本集中前 k">
<meta property="og:type" content="article">
<meta property="og:title" content="K近邻算法的实现">
<meta property="og:url" content="http://sylarchen1389.github.io/2019/05/09/knn/index.html">
<meta property="og:site_name" content="SylarChen的个人博客">
<meta property="og:description" content="原理k 临近算法，是机器学习（监督学习）的一种经典的分类算（当然也能解决其他的一些问题，例如线性回归） 官方解释：存在一个样本数据集，也称作训练样本集，并且样本中每个数据都存在标签，即我们知道样本集中每一数据与所属分类的对应关系，输入没有标签的新数据后，将新数据的每个特征与样本集中的数据对应的特征进行比较，然后算法提取样本集中特征最相似的数据（最近邻）的分类标签。一般来说，我们只选择样本集中前 k">
<meta property="og:locale" content="en">
<meta property="og:image" content="http://sylarchen1389.github.io/2019/05/09/knn/dataset.png">
<meta property="og:image" content="http://sylarchen1389.github.io/2019/05/09/knn/iris_1.png">
<meta property="og:image" content="http://sylarchen1389.github.io/2019/05/09/knn/iris_2.png">
<meta property="og:image" content="http://sylarchen1389.github.io/2019/05/09/knn/train.png">
<meta property="og:image" content="http://sylarchen1389.github.io/2019/05/09/knn/predict.png">
<meta property="og:image" content="http://sylarchen1389.github.io/2019/05/09/knn/score.png">
<meta property="og:image" content="http://sylarchen1389.github.io/2019/05/09/knn/sk_knn.png">
<meta property="og:image" content="http://sylarchen1389.github.io/2019/05/09/knn/sk_knn_2.png">
<meta property="og:image" content="http://sylarchen1389.github.io/2019/05/09/knn/sk_knn_3.png">
<meta property="og:image" content="http://sylarchen1389.github.io/2019/05/09/knn/for.png">
<meta property="og:image" content="http://sylarchen1389.github.io/2019/05/09/knn/p.png">
<meta property="og:image" content="http://sylarchen1389.github.io/2019/05/09/knn/p_2.png">
<meta property="og:updated_time" content="2019-05-10T00:31:23.212Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="K近邻算法的实现">
<meta name="twitter:description" content="原理k 临近算法，是机器学习（监督学习）的一种经典的分类算（当然也能解决其他的一些问题，例如线性回归） 官方解释：存在一个样本数据集，也称作训练样本集，并且样本中每个数据都存在标签，即我们知道样本集中每一数据与所属分类的对应关系，输入没有标签的新数据后，将新数据的每个特征与样本集中的数据对应的特征进行比较，然后算法提取样本集中特征最相似的数据（最近邻）的分类标签。一般来说，我们只选择样本集中前 k">
<meta name="twitter:image" content="http://sylarchen1389.github.io/2019/05/09/knn/dataset.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://sylarchen1389.github.io/2019/05/09/knn/">





  <title>K近邻算法的实现 | SylarChen的个人博客</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta custom-logo">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">SylarChen的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">记录学习日志:)</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://sylarchen1389.github.io/2019/05/09/knn/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Sylar Chen">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/logo.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="SylarChen的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">K近邻算法的实现</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-05-09T22:09:33+08:00">
                2019-05-09
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/机器学习/" itemprop="url" rel="index">
                    <span itemprop="name">机器学习</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Words count in article&#58;</span>
                
                <span title="Words count in article">
                  2.3k
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h1><p>k 临近算法，是机器学习（监督学习）的一种经典的分类算（当然也能解决其他的一些问题，例如线性回归）</p>
<p>官方解释：存在一个样本数据集，也称作训练样本集，并且样本中每个数据都存在标签，即我们知道样本集中每一数据与所属分类的对应关系，输入没有标签的新数据后，将新数据的每个特征与样本集中的数据对应的特征进行比较，然后算法提取样本集中特征最相似的数据（最近邻）的分类标签。一般来说，我们只选择样本集中前 k 个最相似的数据，这就是 k-近邻算法中 k 的出处，通常 k 是不大于 20 的整数，最后，选择 k 个最相似的数据中出现次数最多的分类，作为新数据的分类。</p>
<p>我的理解：将原有样本集视为一个模型（KNN 非常特殊，可以视为没有，为了和其他模型统一，我把原本的数据集理解为一个模型），对于来一个样本，把他放在原数据集中，从它临近的类别来判断它的类别，就好像一朵花周围都是鸢尾花，那这朵花大概率也是鸢尾花（当然鸢尾花也有各种类别，下文就将拿鸢尾花这个经典的数据集来测试我们实现的 K 近邻算法），这里的 K 就是考虑的近邻的个数，是一个超参数。而算法的目的就是找出目标样本最近的 K 个样本，分析各个样本的类别，来决定样本的类别。</p>
<a id="more"></a>
<h1 id="数据准备"><a href="#数据准备" class="headerlink" title="数据准备"></a>数据准备</h1><h4 id="测试数据来源与加载"><a href="#测试数据来源与加载" class="headerlink" title="测试数据来源与加载"></a>测试数据来源与加载</h4><p>这里，我们使用 sklearn 封装好的数据集。<br>sklearn 的数据集有好多个种</p>
<ul>
<li>自带的小数据集（packaged dataset）：sklearn.datasets.load_<name></name></li>
<li>可在线下载的数据集（Downloaded Dataset）：sklearn.datasets.fetch_<name></name></li>
<li>计算机生成的数据集（Generated Dataset）：sklearn.datasets.make_<name></name></li>
<li>svmlight/libsvm 格式的数据集:sklearn.datasets.load_svmlight_file(…)</li>
<li>从买了 data.org 在线下载获取的数据集:sklearn.datasets.fetch_mldata(…)</li>
</ul>
<p>其中自带的小数据集中有</p>
<p><img src="/2019/05/09/knn/dataset.png" alt="dataset"></p>
<!-- <img src="https://raw.githubusercontent.com/sylarchen1389/sylarchen1389.github.io/master/image/578330-20170610195748356-1518693081.png" width = 80% height = 80% div align=center /> -->
<p>这些数据集都可以在官网上查到，以鸢尾花为例，可以在官网上找到 demo，<a href="http://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html" target="_blank" rel="noopener">http://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html</a></p>
<p>我们使用鸢尾花的数据集</p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> datasets</span><br><span class="line">iris=datasets.load_iris()</span><br></pre></td></tr></table></figure>
<p>使用<code>iris.key()</code>我们可以看到输出了<br><img src="/2019/05/09/knn/iris_1.png" alt="iris_1"></p>
<p><code>DESCR</code>是特征的描述</p>
<p><code>feature_names</code>是特征的名字</p>
<p><code>data</code>是特征数据</p>
<p><code>target_names</code>是类别的名称</p>
<p><code>target</code>在此数据集中是鸢尾花的类别</p>
<p>方便后面操作，我们令</p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">X = iris.data</span><br><span class="line">y = iris.target</span><br></pre></td></tr></table></figure>
<p>可以看到：</p>
<p><img src="/2019/05/09/knn/iris_2.png" alt="iris_2"></p>
<p>这个数据集有 150 个样本，4 个特征，可以看到，X 与 Y 的数目是对应的</p>
<p>关于这个数据集的详细内容，可以通过<br><code>print(iris.DESCR)</code><br>来查看，详细内容在 sklearn 官网都有</p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">OUTPUT：</span><br><span class="line"></span><br><span class="line">    .. _iris_dataset:</span><br><span class="line"></span><br><span class="line">    Iris plants dataset</span><br><span class="line">    --------------------</span><br><span class="line"></span><br><span class="line">    **Data Set Characteristics:**</span><br><span class="line"></span><br><span class="line">        :Number of Instances: <span class="number">150</span> (<span class="number">50</span> <span class="keyword">in</span> each of three classes)</span><br><span class="line">        :Number of Attributes: <span class="number">4</span> numeric, predictive attributes <span class="keyword">and</span> the <span class="class"><span class="keyword">class</span></span></span><br><span class="line"><span class="class">        :</span>Attribute Information:</span><br><span class="line">            - sepal length <span class="keyword">in</span> cm</span><br><span class="line">            - sepal width <span class="keyword">in</span> cm</span><br><span class="line">            - petal length <span class="keyword">in</span> cm</span><br><span class="line">            - petal width <span class="keyword">in</span> cm</span><br><span class="line">            - <span class="class"><span class="keyword">class</span>:</span></span><br><span class="line">                    - Iris-Setosa</span><br><span class="line">                    - Iris-Versicolour</span><br><span class="line">                    - Iris-Virginica</span><br><span class="line"></span><br><span class="line">        :Summary Statistics:</span><br><span class="line"></span><br><span class="line">        ============== ==== ==== ======= ===== ====================</span><br><span class="line">                        Min  Max   Mean    SD   Class Correlation</span><br><span class="line">        ============== ==== ==== ======= ===== ====================</span><br><span class="line">        sepal length:   <span class="number">4.3</span>  <span class="number">7.9</span>   <span class="number">5.84</span>   <span class="number">0.83</span>    <span class="number">0.7826</span></span><br><span class="line">        sepal width:    <span class="number">2.0</span>  <span class="number">4.4</span>   <span class="number">3.05</span>   <span class="number">0.43</span>   <span class="number">-0.4194</span></span><br><span class="line">        petal length:   <span class="number">1.0</span>  <span class="number">6.9</span>   <span class="number">3.76</span>   <span class="number">1.76</span>    <span class="number">0.9490</span>  (high!)</span><br><span class="line">        petal width:    <span class="number">0.1</span>  <span class="number">2.5</span>   <span class="number">1.20</span>   <span class="number">0.76</span>    <span class="number">0.9565</span>  (high!)</span><br><span class="line">        ============== ==== ==== ======= ===== ====================</span><br><span class="line"></span><br><span class="line">        :Missing Attribute Values: <span class="keyword">None</span></span><br><span class="line">        :Class Distribution: <span class="number">33.3</span>% <span class="keyword">for</span> each of <span class="number">3</span> classes.</span><br><span class="line">        .....</span><br></pre></td></tr></table></figure>
<h1 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h1><h4 id="距离的定义"><a href="#距离的定义" class="headerlink" title="距离的定义"></a>距离的定义</h4><p>首先，K 近邻算法需要找到离预测样本最近的 K 个样本，那么我们就需要先明确什么是距离</p>
<p>对于大部分人来说，我们最熟悉就是欧拉距离了<br>$$\sqrt[2]{\sum_{i=0}^N(x_i^{(a)} - x_i^{(b)})^2}$$</p>
<p>将指数改为 1，我们就得到了曼哈顿距离<br>$$\sum_{i=0}^N\ |x_i^{(a)} - x_i^{(b)}|$$</p>
<p>读到这里，大家或许在想，为什么我们不干脆改成 n？没错，这时候我们得到了明可夫斯基距离，同时获得了一个超参数 n<br>$$\sqrt[n]{\sum_{i=0}^N(x_i^{(a)} - x_i^{(b)})^n}$$<br>下面的代码实现，我用大家都比较熟悉的欧拉距离实现</p>
<h4 id="Code-python"><a href="#Code-python" class="headerlink" title="Code (python)"></a>Code (python)</h4><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">from</span> math <span class="keyword">import</span> sqrt</span><br><span class="line"><span class="keyword">from</span> collections <span class="keyword">import</span> Counter</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">KNNClassifier</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, k)</span>:</span></span><br><span class="line">        <span class="string">"""初始化kNN分类器"""</span></span><br><span class="line">        <span class="keyword">assert</span> k &gt;= <span class="number">1</span>, <span class="string">"k must be valid"</span></span><br><span class="line">        self.k = k</span><br><span class="line">        <span class="string">"""需要注意的是，因为kNN是典型的非参数\</span></span><br><span class="line"><span class="string">        学习算法，对于这个算法，我们需要有成员\</span></span><br><span class="line"><span class="string">        来储存已有的数据"""</span></span><br><span class="line">        self._X_train = <span class="keyword">None</span></span><br><span class="line">        self._y_train = <span class="keyword">None</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">fit</span><span class="params">(self, X_train, y_train)</span>:</span></span><br><span class="line">        <span class="string">"""根据训练数据集X_train和y_train训练kNN分类器"""</span></span><br><span class="line">        <span class="keyword">assert</span> X_train.shape[<span class="number">0</span>] == y_train.shape[<span class="number">0</span>], \</span><br><span class="line">            <span class="string">"the size of X_train must be equal to the size of y_train"</span></span><br><span class="line">        <span class="keyword">assert</span> self.k &lt;= X_train.shape[<span class="number">0</span>], \</span><br><span class="line">            <span class="string">"the size of X_train must be at least k."</span></span><br><span class="line"></span><br><span class="line">        self._X_train = X_train</span><br><span class="line">        self._y_train = y_train</span><br><span class="line">        <span class="keyword">return</span> self</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">predict</span><span class="params">(self, X_predict)</span>:</span></span><br><span class="line">        <span class="string">"""给定待预测数据集X_predict，返回表示X_predict的结果向量"""</span></span><br><span class="line">        <span class="keyword">assert</span> self._X_train <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span> <span class="keyword">and</span> self._y_train <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>, \</span><br><span class="line">                <span class="string">"must fit before predict!"</span></span><br><span class="line">        <span class="keyword">assert</span> X_predict.shape[<span class="number">1</span>] == self._X_train.shape[<span class="number">1</span>], \</span><br><span class="line">                <span class="string">"the feature number of X_predict must be equal to X_train"</span></span><br><span class="line"></span><br><span class="line">        y_predict = [self._predict(x) <span class="keyword">for</span> x <span class="keyword">in</span> X_predict]</span><br><span class="line">        <span class="keyword">return</span> np.array(y_predict)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_predict</span><span class="params">(self, x)</span>:</span></span><br><span class="line">        <span class="string">"""给定单个待预测数据x，返回x的预测结果值"""</span></span><br><span class="line">        <span class="keyword">assert</span> x.shape[<span class="number">0</span>] == self._X_train.shape[<span class="number">1</span>], \</span><br><span class="line">            <span class="string">"the feature number of x must be equal to X_train"</span></span><br><span class="line"></span><br><span class="line">        distances = [sqrt(np.sum((x_train - x) ** <span class="number">2</span>))</span><br><span class="line">                     <span class="keyword">for</span> x_train <span class="keyword">in</span> self._X_train]</span><br><span class="line">        nearest = np.argsort(distances)</span><br><span class="line"></span><br><span class="line">        topK_y = [self._y_train[i] <span class="keyword">for</span> i <span class="keyword">in</span> nearest[:self.k]]</span><br><span class="line">        votes = Counter(topK_y)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> votes.most_common(<span class="number">1</span>)[<span class="number">0</span>][<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">accuracy_score</span><span class="params">(y_true, y_predict)</span>:</span></span><br><span class="line">    <span class="string">'''计算y_true和y_predict之间的准确率'''</span></span><br><span class="line">    <span class="keyword">assert</span> y_true.shape[<span class="number">0</span>] == y_predict.shape[<span class="number">0</span>], \</span><br><span class="line">    <span class="string">"the size of y_true must be equal to the size of y_predict"</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> sum(y_true == y_predict) / len(y_true)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">score</span><span class="params">(self, X_test, y_test)</span>:</span></span><br><span class="line">        <span class="string">"""根据测试数据集 X_test 和 y_test 确定当前模型的准确度"""</span></span><br><span class="line"></span><br><span class="line">        y_predict = self.predict(X_test)</span><br><span class="line">        <span class="keyword">return</span> accuracy_score(y_test, y_predict)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__repr__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">"KNN(k=%d)"</span> % self.k</span><br></pre></td></tr></table></figure>
<h1 id="测试我们的算法"><a href="#测试我们的算法" class="headerlink" title="测试我们的算法"></a>测试我们的算法</h1><h3 id="数据分割（train-test-split）"><a href="#数据分割（train-test-split）" class="headerlink" title="数据分割（train_test_split）"></a>数据分割（train_test_split）</h3><p>这里做一个操作，将原先的数据集 X 和 y 按照 0.2 分割成 X_train, X_test, y_train, y_test<br>（len(x_train) = 0.8 *len(x)）,方便后面对我们的算法进行简单的测试</p>
<p><img src="/2019/05/09/knn/train.png" alt="train"></p>
<p>代码就不贴在这了，有兴趣的读者可以访问我的 github 查看</p>
<h3 id="训练（拟合）"><a href="#训练（拟合）" class="headerlink" title="训练（拟合）"></a>训练（拟合）</h3><p>我们先声明一个我们封装的类的对象，<br>再调用 fit 函数训练</p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">my_knn_clf = KNNClassifier(k=<span class="number">3</span>)</span><br><span class="line">my_knn_clf.fit(X_train,y_train)</span><br></pre></td></tr></table></figure>
<h3 id="预测"><a href="#预测" class="headerlink" title="预测"></a>预测</h3><p>直接调用我们写的 predict 函数</p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">y_predict=my_knn_clf.predict(X_test)</span><br></pre></td></tr></table></figure>
<p><img src="/2019/05/09/knn/predict.png" alt="predict"></p>
<h1 id="评测（正确率）"><a href="#评测（正确率）" class="headerlink" title="评测（正确率）"></a>评测（正确率）</h1><p>对于鸢尾花这个数据集，最简单的计算计算计算正确率的方法就是与原数据中的 y 比较，一样则分类正确。我们将其加起来，再除以测试样本的数量，就得到了一个简单的评判标准。<br><img src="/2019/05/09/knn/score.png" alt="score"></p>
<h1 id="调用-sklearn-实现-KNN"><a href="#调用-sklearn-实现-KNN" class="headerlink" title="调用 sklearn 实现 KNN"></a>调用 sklearn 实现 KNN</h1><p>sklearn 是一个机器学习的库，封装了许多机器学习算法，我们可以直接通过调库来使用相关的算法</p>
<p>我们通过<code>from sklearn.neighbors import KNeighborsClassifier</code>来加载 sklearn 封装的 KNN 分类器</p>
<p>然后与上面的操作相同，我们先声明对象，再调用它封装的 fit 函数训练</p>
<p><img src="/2019/05/09/knn/sk_knn.png" alt="sk_knn"></p>
<p>同样，sklearn 也为分类器封装了 predict 函数，我们可以直接调用 predict 函数来对预测样本进行分类</p>
<p><img src="/2019/05/09/knn/sk_knn_2.png" alt="sk_knn_2"></p>
<p>我们调 sklearn 封装的 score 函数来测试算法的正确率</p>
<p><img src="/2019/05/09/knn/sk_knn_3.png" alt="sk_knn_3"></p>
<p>当然，sklearn 对 score 函数的实现方式不同，所以评价标准也不同，即使我们自己实现的 kNN 比 sklearn 的 kNN 得分高，但我们不能说我们的算法比 sklearn 封装的算法好，因为评判标准是不一样的。实际上，如何选择出对于当前问题最合适的算法，也是机器学习的一个难题</p>
<h1 id="超参数"><a href="#超参数" class="headerlink" title="超参数"></a>超参数</h1><p>超参数的调节是机器学习的一个重要问题，下面举了几个我们实现的算法中出现的超参数，对于如何获取这些超参数的最优值，我会用一些比较简单但时间复杂度可能稍高的方法，其他方法请有兴趣的读者们自行查找</p>
<p>这里对于超参数的搜索，我们使用 sklearn 封装的 KNN 算法.</p>
<h4 id="k"><a href="#k" class="headerlink" title="k"></a>k</h4><p>最明显的超参数，就是我<br>们要搜索的近邻的个数 k，到底要检测周围多少个点，才能是我们的算法得到最好的正确率？</p>
<p>sklearn 中使用的变量名为 n_neighbor</p>
<p>我们可以简单地写一个 for 循环测试一下<br><img src="/2019/05/09/knn/for.png" alt="for"></p>
<p>可以看到这里显示最好的 k 是 4，而准确率是 0.99166…..</p>
<h4 id="距离"><a href="#距离" class="headerlink" title="距离"></a>距离</h4><p>我们的算法寻找 k 个最近的近邻的标签进行比较，那么距离的远近是否需要考虑呢？比如距离大一点的样本，对预测的样本的影响比较小，那我们可以给一个比较小的权值，距离比较小的我们就可以给一个较大的权值</p>
<p>sklearn 中对于是否考虑距离，使用变量 weight，值为 unifrom（不考虑）和 distance（考虑）</p>
<p>我们同样使用 for 循环进行简单的搜索</p>
<p><img src="/2019/05/09/knn/p.png" alt="p"></p>
<h4 id="明可夫斯基距离相应的-n"><a href="#明可夫斯基距离相应的-n" class="headerlink" title="明可夫斯基距离相应的 n"></a>明可夫斯基距离相应的 n</h4><p>sklearn 中对于明可夫斯基距离相应的 n 使用变量 p 表示，同样我们使用一个 for 循环搜索</p>
<p><img src="/2019/05/09/knn/p_2.png" alt="p_2"></p>
<h4 id="其他的超参数"><a href="#其他的超参数" class="headerlink" title="其他的超参数"></a>其他的超参数</h4><p>可以查看 sklearn 官网对于 KNN 的算法的手册<br><a href="http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.DistanceMetric.html" target="_blank" rel="noopener">http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.DistanceMetric.html</a></p>

      
    </div>
    
    
    

    <div>
        
            <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束-------------</div>
    
</div>

        
    </div>

    

    

    

    <footer class="post-footer">
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/04/21/knight_journery/" rel="next" title="knight's journey(dfs)">
                <i class="fa fa-chevron-left"></i> knight's journey(dfs)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/logo.jpg" alt="Sylar Chen">
            
              <p class="site-author-name" itemprop="name">Sylar Chen</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/sylarchen1389" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:1468926537@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#原理"><span class="nav-number">1.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#数据准备"><span class="nav-number">2.</span> <span class="nav-text">数据准备</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#测试数据来源与加载"><span class="nav-number">2.0.0.1.</span> <span class="nav-text">测试数据来源与加载</span></a></li></ol></li></ol><li class="nav-item nav-level-1"><a class="nav-link" href="#实现"><span class="nav-number">3.</span> <span class="nav-text">实现</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#距离的定义"><span class="nav-number">3.0.0.1.</span> <span class="nav-text">距离的定义</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Code-python"><span class="nav-number">3.0.0.2.</span> <span class="nav-text">Code (python)</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#测试我们的算法"><span class="nav-number">4.</span> <span class="nav-text">测试我们的算法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#数据分割（train-test-split）"><span class="nav-number">4.0.1.</span> <span class="nav-text">数据分割（train_test_split）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#训练（拟合）"><span class="nav-number">4.0.2.</span> <span class="nav-text">训练（拟合）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#预测"><span class="nav-number">4.0.3.</span> <span class="nav-text">预测</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#评测（正确率）"><span class="nav-number">5.</span> <span class="nav-text">评测（正确率）</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#调用-sklearn-实现-KNN"><span class="nav-number">6.</span> <span class="nav-text">调用 sklearn 实现 KNN</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#超参数"><span class="nav-number">7.</span> <span class="nav-text">超参数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#k"><span class="nav-number">7.0.0.1.</span> <span class="nav-text">k</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#距离"><span class="nav-number">7.0.0.2.</span> <span class="nav-text">距离</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#明可夫斯基距离相应的-n"><span class="nav-number">7.0.0.3.</span> <span class="nav-text">明可夫斯基距离相应的 n</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#其他的超参数"><span class="nav-number">7.0.0.4.</span> <span class="nav-text">其他的超参数</span></a></li></ol></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Sylar Chen</span>

  
</div>

<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站总访问量<span id="busuanzi_value_site_uv"></span>次
</span>
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
